#include "dht11.h"
static void delay_us(uint8_t us);
static uint8_t read_bit(GPIO_TypeDef*,uint16_t);
static void set_input(GPIO_TypeDef*,uint16_t);
static void set_output(GPIO_TypeDef*,uint16_t);
static uint8_t read_byte(GPIO_TypeDef*,uint16_t);
static int8_t  check(GPIO_TypeDef*,uint16_t);
static int8_t check(GPIO_TypeDef* port,uint16_t pin)
{
	uint8_t retry=0;
    while (HAL_GPIO_ReadPin(port,pin)&&retry<100)
	{
		retry++;
		delay_us(1);
	};	 
	if(retry>=100)return 1;
	else retry=0;
    while (!HAL_GPIO_ReadPin(port,pin)&&retry<100)
	{
		retry++;
		delay_us(1);
	};
	if(retry>=100)return 1;	    
	return 0;
}
int8_t DHT11_Get_HT(float* vh,float*vt,GPIO_TypeDef* port,uint16_t pin)
{
	uint8_t rbuff[5] = {0};
	//1.reset
	set_output(port,pin);
	HAL_GPIO_WritePin(port,pin,GPIO_PIN_RESET);
	osDelay(20);
	set_input(port,pin);
	//2.
	if(check(port,pin) == 0)
	{
		for(uint8_t i=0;i<5;i++)
			rbuff[i] = read_byte(port,pin);
		if( (rbuff[0] + rbuff[1] + rbuff[2] + rbuff[3]) == rbuff[4])
		{
			*vh=rbuff[0] + rbuff[1]/10.0;
			if(rbuff[3]&0x80)
				*vt = -(rbuff[2] + (rbuff[3]&0x7f)/10.0);
			else
				*vt=rbuff[2] + rbuff[3]/10.0;
			return 0;
		}
	}
	return 1;
}
static void delay_us(uint8_t us)
{
   volatile uint16_t t=0;  
   while(us--)
   {
      t=2;
      while(t--) ;    
   }
}
static uint8_t read_bit(GPIO_TypeDef* port,uint16_t pin)
{
	uint8_t retry=0;
	while( HAL_GPIO_ReadPin(port,pin)&&retry<100)
	{
		retry++;
		delay_us(1);
	}
	retry=0;
	while(!HAL_GPIO_ReadPin(port,pin)&&retry<100)
	{
		retry++;
		delay_us(1);
	}
	delay_us(40);//??40us
	if(HAL_GPIO_ReadPin(port,pin))return 1;
	else return 0;		   
}
static void set_input(GPIO_TypeDef* port,uint16_t pin)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	__HAL_RCC_GPIOB_CLK_ENABLE();
    GPIO_InitStruct.Pin = pin;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(port, &GPIO_InitStruct);
}
static void set_output(GPIO_TypeDef* port,uint16_t pin)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	__HAL_RCC_GPIOB_CLK_ENABLE();
    GPIO_InitStruct.Pin = pin;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(port, &GPIO_InitStruct);
}
static uint8_t read_byte(GPIO_TypeDef* port,uint16_t pin)
{
    uint8_t i = 0,dat = 0;
	for (i=0;i<8;i++) 
	{
   		dat<<=1; 
	    dat|=read_bit(port,pin);
    }						    
    return dat;
}











